import { BrowserWindow } from 'electron';
import { asyncChannels } from './asyncChannels';
import Axios from 'axios';
import { capital } from './util'
import IpcMain = Electron.IpcMain

export function httpListener(window: BrowserWindow) {
    const ipcMain = require('electron').ipcMain;

    register1(ipcMain, 'request');

    register2(ipcMain, 'get');
    register2(ipcMain, 'delete');
    register2(ipcMain, 'head');

    register3(ipcMain, 'post');
    register3(ipcMain, 'put');
    register3(ipcMain, 'patch');
}

function register1(ipcMain: IpcMain, method: string) {
    const channel = asyncChannels[`http${capital(method)}`];
    const replyChannel = asyncChannels[`http${capital(method)}Reply`];

    ipcMain.on(channel, async (event, uid, config) => {
        let resp;
        let error;
        try {
            resp = await Axios[method](config);
        } catch (e) {
            error = e;
        } finally {
            event.sender.send(replyChannel, uid, [resp, error]);
        }
    });
}

function register2(ipcMain: IpcMain, method: string) {
    const channel = asyncChannels[`http${capital(method)}`];
    const replyChannel = asyncChannels[`http${capital(method)}Reply`];

    ipcMain.on(channel, async (event, uid, url, config) => {
        let resp;
        let error;
        try {
            resp = await Axios[method](url, config);
        } catch (e) {
            error = e;
        } finally {
            event.sender.send(replyChannel, uid, [resp, error]);
        }
    });
}

function register3(ipcMain: IpcMain, method: string) {
    const channel = asyncChannels[`http${capital(method)}`];
    const replyChannel = asyncChannels[`http${capital(method)}Reply`];

    ipcMain.on(channel, async (event, uid, url, data, config) => {
        let resp;
        let error;
        try {
            resp = await Axios[method](url, data, config);
        } catch (e) {
            error = e;
        } finally {
            event.sender.send(replyChannel, uid, [resp, error]);
        }
    });
}
